<?php

class Librarian_BookController extends Zend_Controller_Action
{

    public function indexAction()
    {
        $page = $this->getRequest()->getParam('page', 1);

        $q = trim($this->getRequest()->getParam('q', ''));
        
        if ($q)
        {
            $books = Model_Book::find(array(
                'q' => $q,
                'Status' => 1,
                'Page' => $page,
                'Limit' => 10
            ), $total);
        }
        else
        {
            $books = Model_Book::getAll(array(
                'Type'   => 1,
                'Status' => 1,
                'Page'   => $page,
                'Limit'  => 10
            ), $total);
        }
        
        $paginator = Core_Paginator::get($total, $page);                
        
        $this->view->assign('pagination', $paginator);
        
        $this->view->assign('q', $q);
        $this->view->assign('books', $books);
    }

    public function createAction()
    {
        if ($this->getRequest()->isPost())
        {
            try
            {
                $response = array(
                    'status'  => 0,
                    'message' => 'Unknown error...'
                );

                $cover = null;

                $adapter = new Zend_File_Transfer_Adapter_Http();

                $files = $adapter->getFileInfo();

                if (!empty($files['Cover']))
                {
                    $adapter->addValidator('FilesSize', false, 2000000)->addValidator('Extension', false, array('jpg', 'gif', 'png'));
                    if ($adapter->isValid())
                    {
                        $path       = realpath(UPLOAD_PATH . '/covers');
                        $extension  = pathinfo($adapter->getFileName('Cover', false), PATHINFO_EXTENSION);
                        $filename   = pathinfo($adapter->getFileName('Cover', false), PATHINFO_FILENAME);
                        $hashedname = md5($filename . uniqid()) . '.' . $extension;
                        $target     = $path . '/' . $hashedname;
                        $adapter->addFilter('Rename', array('target'    => $target, 'overwrite' => true));
                        // Upload
                        if (!$adapter->receive())
                        {
                            $response['message'] = implode("\n", $adapter->getMessages());
                            $this->_helper->json($response);
                        }

                        // Resize - Create thumbnail
                        $imgLib = new Core_Image(array(
                                    'image_library'  => 'gd2',
                                    'source_image'   => $target,
                                    'create_thumb'   => TRUE,
                                    'maintain_ratio' => TRUE,
                                    'new_image'      => str_replace('covers/', 'covers/thumb/', $target),
                                    'thumb_marker'   => '',
                                    'quality'        => '100%',
                                    'master_dim'     => 'height',
                                    'width'          => 100,
                                    'height'         => 125
                                ));

                        if (!$imgLib->resize())
                        {
                            $response['message'] = $imgLib->display_errors();
                            $this->_helper->json($response);
                        }

                        $cover = $hashedname;
                    }
                    else
                    {
                        $response['message'] = implode("\n", $adapter->getMessages());
                        $this->_helper->json($response);
                    }
                }

                $params = $this->getRequest()->getPost();

                $params['Cover']       = $cover;
                $params['Title']       = trim($params['Title']);
                $params['PublisherID'] = intval($params['PublisherID']);
                $params['AuthorID']    = array_filter(array_unique($params['AuthorID']));
                $params['CategoryID']  = array_filter(array_unique($params['CategoryID']));
                $params['Quantity']    = intval($params['Quantity']);

                if (!$params['Title'] || strlen($params['Title']) > 200)
                {
                    $response['message'] = 'Tên sách phải từ 1 - 200 ký tự.';
                }
                else if (!$params['PublisherID'])
                {
                    $response['message'] = 'Bạn chưa chọn nhà xuất bản.';
                }
                else if (empty($params['AuthorID']))
                {
                    $response['message'] = 'Bạn chưa chọn tác giả.';
                }
                else if (empty($params['CategoryID']))
                {
                    $response['message'] = 'Bạn chưa chọn chuyên mục.';
                }
                else if ($params['Quantity'] < 0)
                {
                    $response['message'] = 'Số lương phải >= 0.';
                }
                else
                {
                    try
                    {
                        if (Model_Book::create($params))
                        {
                            $response['status']  = 1;
                            $response['message'] = 'Success';
                        }
                    }
                    catch (Zend_Db_Exception $e)
                    {
                        $response['message'] = $e->getMessage();
                    }
                }

                $this->_helper->json($response);
            }
            catch (Zend_Exception $e)
            {
                var_dump($e);
            }
        }

        $this->view->publishers = Model_Publisher::getAll();
        $this->view->authors = Model_Author::getAll();
        $this->view->categories = Model_Category::getAll();
    }

    public function editAction()
    {
        if ($this->getRequest()->isPost())
        {
            try
            {
                $response = array(
                    'status'  => 0,
                    'message' => 'Unknown error...'
                );

                $params = $this->getRequest()->getPost();

                if (!$params['BookID'])
                {
                    $response['message'] = 'Bạn chưa chọn sách để chỉnh sửa.';
                    $this->_helper->json($response);
                }

                $cover = $params['CoverPath'] ? $params['CoverPath'] : null;

                $adapter = new Zend_File_Transfer_Adapter_Http();

                $files = $adapter->getFileInfo();

                if (!empty($files['Cover']))
                {
                    $adapter->addValidator('FilesSize', false, 2000000)->addValidator('Extension', false, array('jpg', 'gif', 'png'));
                    if ($adapter->isValid())
                    {
                        $path       = realpath(UPLOAD_PATH . '/covers');
                        $extension  = pathinfo($adapter->getFileName('Cover', false), PATHINFO_EXTENSION);
                        $filename   = pathinfo($adapter->getFileName('Cover', false), PATHINFO_FILENAME);
                        $hashedname = md5($filename . uniqid()) . '.' . $extension;
                        $target     = $path . '/' . $hashedname;
                        $adapter->addFilter('Rename', array('target'    => $target, 'overwrite' => true));
                        // Upload
                        if (!$adapter->receive())
                        {
                            $response['message'] = implode("\n", $adapter->getMessages());
                            $this->_helper->json($response);
                        }

                        // Resize - Create thumbnail
                        $imgLib = new Core_Image(array(
                                    'image_library'  => 'gd2',
                                    'source_image'   => $target,
                                    'create_thumb'   => TRUE,
                                    'maintain_ratio' => TRUE,
                                    'new_image'      => str_replace('covers/', 'covers/thumb/', $target),
                                    'thumb_marker'   => '',
                                    'quality'        => '100%',
                                    'master_dim'     => 'height',
                                    'width'          => 100,
                                    'height'         => 125
                                ));

                        if (!$imgLib->resize())
                        {
                            $response['message'] = $imgLib->display_errors();
                            $this->_helper->json($response);
                        }

                        //Remove old images                        
                        @unlink(UPLOAD_PATH . '/covers/' . $cover);
                        @unlink(UPLOAD_PATH . '/covers/thumb/' . str_replace('.', '_thumb.', $cover));

                        $cover = $hashedname;
                    }
                    else
                    {
                        $response['message'] = implode("\n", $adapter->getMessages());
                        $this->_helper->json($response);
                    }
                }

                $params['Cover']       = $cover;
                $params['Title']       = trim($params['Title']);
                $params['PublisherID'] = intval($params['PublisherID']);
                $params['AuthorID']    = array_filter(array_unique($params['AuthorID']));
                $params['CategoryID']  = array_filter(array_unique($params['CategoryID']));
                $params['Quantity']    = intval($params['Quantity']);

                if (!$params['Title'] || strlen($params['Title']) > 200)
                {
                    $response['message'] = 'Tên sách phải từ 1 - 200 ký tự.';
                }
                else if (!$params['PublisherID'])
                {
                    $response['message'] = 'Bạn chưa chọn nhà xuất bản.';
                }
                else if (empty($params['AuthorID']))
                {
                    $response['message'] = 'Bạn chưa chọn tác giả.';
                }
                else if (empty($params['CategoryID']))
                {
                    $response['message'] = 'Bạn chưa chọn chuyên mục.';
                }
                else if ($params['Quantity'] < 0)
                {
                    $response['message'] = 'Số lương phải >= 0.';
                }
                else
                {
                    try
                    {
                        if (Model_Book::edit($params))
                        {
                            $response['status']  = 1;
                            $response['message'] = 'Success';
                            $this->_helper->FlashMessenger->addMessage('Chỉnh sửa sách thành công!');
                        }
                    }
                    catch (Zend_Db_Exception $e)
                    {
                        $response['message'] = $e->getMessage();
                    }
                }

                $this->_helper->json($response);
            }
            catch (Zend_Exception $e)
            {
                var_dump($e);
            }
        }

        $params = $this->getRequest()->getParams();

        if (!intval($params['book_id']))
        {
            $this->_redirect('/librarian/book');
        }

        $book = Model_Book::get($params);
        
        if (empty($book))
        {
            $this->_redirect('/librarian/book');
        }

        $book['AuthorID']   = array_unique(explode(',', $book['AuthorID']));
        $book['CategoryID'] = array_unique(explode(',', $book['CategoryID']));

        $this->view->publishers = Model_Publisher::getAll();
        $this->view->authors = Model_Author::getAll();
        $this->view->categories = Model_Category::getAll();
        $this->view->assign('book', $book);
    }

    public function deleteAction()
    {
        if ($this->getRequest()->isPost())
        {
            $response = array(
                'status'  => 0,
                'message' => 'Unknown error...'
            );

            $params = $this->getRequest()->getPost();

            if (!intval($params['BookID']))
            {
                $response['message'] = 'Bạn chưa chọn sách để xoá.';
            }
            else
            {
                try
                {
                    $affected = Model_Book::delete($params);

                    if ($affected)
                    {
                        $response['status']  = 1;
                        $response['message'] = 'Success';
                    }
                }
                catch (Zend_Db_Exception $e)
                {
                    $response['message'] = $e->getMessage();
                }
            }

            $this->_helper->json($response);
        }
    }

}
